package com.eascs.ant.user.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eascs.ant.common.service.BaseSevice;
import com.eascs.ant.user.dao.UserDao;
import com.eascs.ant.user.entity.User;
import com.eascs.common.util.StringUtil;

@Service
public class UserService extends BaseSevice {

	@Inject
	private UserDao userDao;

	public List<Object[]> getValidUserDataSouceList() {
		return userDao.getValidUserDataSouceList();
	}

	public List<Object[]> getAllUserDataSouceList() {
		return userDao.getAllUserDataSouceList();
	}

	public List<User> getAllUser() {
		return this.proxyDao.findAllEntitys(User.class);
	}

	public List<User> getUsersByCodes(String[] codes) {
		StringBuffer sql = new StringBuffer(60);
		sql.append("select * from user where 1=1 and code in (");
		for (int i = 0; i < codes.length; i++) {
			if (i > 0)
				sql.append(',');
			sql.append('?');
		}
		sql.append(") order by code");
		return this.proxyDao.findEntitys(sql.toString(), User.class, Arrays.asList(codes).toArray());
	}

	public User getUserByCode(String userCode) {
		return userDao.getUserByCode(userCode);
	}

	public List<Object[]> searchUserByWord(String searchWord) {
		if (StringUtil.isEmpty(searchWord)) {
			return new ArrayList<>();
		}
		String word = "%" + searchWord + "%";
		return this.proxyDao.findObjectsList("select code,name from user where name like ? or login_name like ? or code like ? limit 10", word, word, word);
	}

	public User getUserByLoginName(String loginName) {
		User userQuery = new User();
		userQuery.setLoginName(loginName);
		userQuery = this.proxyDao.findEntityWithAny(userQuery);
		return userQuery;
	}

	@Transactional(transactionManager = "ticketTransactionManager")
	public void saveUser(User user) {
		User userQuery = getUserByCode(user.getCode());
		if (null == userQuery) {
			// EntityUtil.initInsertEntity(user);
			this.proxyDao.insert(user);
		}
	}

	public User getLeaderByUserCode(String userCode) {
		// 如果是团队负责人直接返回
		if (this.proxyDao.findInteger("select count(1) from user_structure where parent_user_code=?", userCode) > 0)
			return null;
		return getSupeiorByUserCode(userCode);
	}

	public User getSupeiorByUserCode(String userCode) {
		// 取该人的团队负责人
		return this.proxyDao.findEntity("select u.* from user u where u.code in (select us.parent_user_code from user_structure us where us.user_code=?)", User.class, userCode);
	}

	public boolean isSupeior(String userCode, String parentUserCode) {
		return this.proxyDao.findInteger("select count(1) from user_structure us where us.user_code=? and us.parent_user_code=?", userCode, parentUserCode) > 0;
	}

}
